package com.xiaobaibai.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xiaobaibai.common.IndexEnum;
import com.xiaobaibai.entity.Category;
import com.xiaobaibai.entity.IndexDetail;
import com.xiaobaibai.entity.IndexProduct;
import com.xiaobaibai.response.ResponseFormat;
import com.xiaobaibai.service.ICategoryService;
import com.xiaobaibai.service.IIndexDetailService;
import com.xiaobaibai.service.IIndexProductService;
import com.xiaobaibai.units.IndexDetailListSortUnit;
import com.xiaobaibai.units.RedisUnit;
import com.xiaobaibai.valid.AddGroup;
import com.xiaobaibai.valid.UpdateGroup;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;

//500
@RestController
@Api(tags = "首页管理相关接口")
@RequestMapping("/index")
@CrossOrigin
public class IndexController {

    /**
     * 首页控制
     * 1.九宫格+轮播图+推广图(单独大图)->九宫格仅可设置分类,轮播图(商品/活动页面)怎么区分跳转呢?推广图(商品/活动页面)
     * 2.新品上市+精品热销->在商品
     * 3.公告
     */

    @Autowired
    private IIndexDetailService iIndexDetailService;

    @Autowired
    private IIndexProductService indexProductService;

    @Autowired
    private RedisUnit redis;

    @Autowired
    private ICategoryService categoryService;

    /**
     * 获取首页所有数据
     */
    @GetMapping("/list")
    @ApiOperation("获取首页基本数据接口")
    public ResponseFormat index(){
        //大图
        List<IndexDetail> detailList = iIndexDetailService.list();
        //商品
//        List<IndexProduct> productsList = indexProductService.list();
        //公告
//        String gongGao = redis.getString(IndexEnum.GONGGAO.getMsg());

        List<IndexDetail> lunBo=new ArrayList<>();
        List<IndexDetail> gongGe=new ArrayList<>();
        List<IndexDetail> daTu=new ArrayList<>();
        detailList.forEach(d->{
            //取出宫格+轮播+推广
            if(d.getType().equals(IndexEnum.GONGGE.getCode())){
                //宫格
                gongGe.add(d);
            }else if(d.getType().equals(IndexEnum.LUNBO.getCode())){
                //轮播
                lunBo.add(d);
            }else if(d.getType().equals(IndexEnum.DATU.getCode())){
                //大图
                daTu.add(d);
            }
        });

        /**
         * 排序一番
         */
        sortList(lunBo);
        sortList(gongGe);


//        List<IndexProduct> xinPin=new ArrayList<>();
//        List<IndexProduct> reXiao=new ArrayList<>();
//        productsList.forEach(p->{
//            if(p.getType().equals(IndexEnum.XINPIN.getCode())){
//                xinPin.add(p);
//            }else{
//                reXiao.add(p);
//            }
//        });

        Map<String,Object> map=new HashMap<>();
        map.put(IndexEnum.LUNBO.getName(),lunBo);
        map.put(IndexEnum.GONGGE.getName(),gongGe);
        map.put(IndexEnum.DATU.getName(),daTu);
//        map.put(IndexEnum.XINPIN.getName(),xinPin);
//        map.put(IndexEnum.REXIAO.getName(),reXiao);
//        map.put(IndexEnum.GONGGE.getName(),gongGao);

        return ResponseFormat.ok("首页数据请求成功",map);
    }

    private IndexDetailListSortUnit sortUnit=new IndexDetailListSortUnit();

    private void sortList(List<IndexDetail> list){
        list.sort(sortUnit);
    }

    //九宫格+轮播图+推广图
    @PostMapping("/do-indexDetail")//添加
    @ApiOperation("添加indexDetail的接口(九宫格,轮播图,推广图)")
    @CacheEvict(value = "indexDetail",key = "'getIndexDetailMap'")
    public ResponseFormat addIndexDetail(@RequestBody @Validated(value = AddGroup.class)
                                                     IndexDetail indexDetail){
        /**
         * 如果是九宫格需要验证是否满了,轮播图是否大于等于5个,推广图是否已经有了 如果满足,那么状态就不能是显示
         * 不过我已经全部默认不显示了
         */

        Integer type=indexDetail.getType();

        if(type.equals(IndexEnum.LUNBO.getCode())){
            //轮播
            QueryWrapper<IndexProduct> queryWrapper=new QueryWrapper<>();
            queryWrapper.eq("type",IndexEnum.LUNBO.getCode());
            int count = indexProductService.count(queryWrapper);
            if(count>=5)
                return ResponseFormat.failure("轮播图已满,请删除后再添加");
        }else if(type.equals(IndexEnum.GONGGE.getCode())){
            //分类
            QueryWrapper<IndexProduct> queryWrapper=new QueryWrapper<>();
            queryWrapper.eq("type",IndexEnum.GONGGE.getCode());
            int count = indexProductService.count(queryWrapper);
            if(count>=5)
                return ResponseFormat.failure("分类宫格已满,请删除后再添加");
        }else{
            //大图
            QueryWrapper<IndexProduct> queryWrapper=new QueryWrapper<>();
            queryWrapper.eq("type",IndexEnum.DATU.getCode());
            int count = indexProductService.count(queryWrapper);
            if(count>=1)
                return ResponseFormat.failure("大图已满,请删除后再添加");
        }

        //对于分类单独进行操作
        if(indexDetail.getType().equals(IndexEnum.GONGGE.getCode())){
            Category category = categoryService.getById(indexDetail.getUrl());
            indexDetail.setImage(category.getCategoryImage());
            indexDetail.setName(category.getCategoryName());
        }

//        indexDetail.setStatus(true);//状态已经废弃
        boolean flag = iIndexDetailService.save(indexDetail);
        if(!flag)
            return ResponseFormat.failure("插入失败,数据库错误");
        return ResponseFormat.ok("添加成功",indexDetail);
    }

    @PutMapping("/do-indexDetail")//修改
    @ApiOperation("修改indexDetail的接口(九宫格,轮播图,推广图)")
    @CacheEvict(value = "indexDetail",key = "'getIndexDetailMap'")
    public ResponseFormat updateIndexDetail(@RequestBody @Validated(value = UpdateGroup.class)
                                                        IndexDetail indexDetail){
        boolean flag = iIndexDetailService.updateById(indexDetail);
        if(!flag)
            return ResponseFormat.failure("修改失败,数据库错误");
        return ResponseFormat.ok("修改成功");
    }

    @DeleteMapping("/do-indexDetail")//删除
    @ApiOperation("删除indexDetail的接口(九宫格,轮播图,推广图)")
    @CacheEvict(value = "indexDetail",key = "'getIndexDetailMap'")
    public ResponseFormat deleteIndexDetail(@RequestParam(value = "id")String id){
        boolean flag = iIndexDetailService.removeById(id);
        if(!flag)
            return ResponseFormat.failure("删除失败,数据库错误");
        return ResponseFormat.ok("删除成功");
    }

    //IndexProduct表
    @PostMapping("/do-indexProduct")//添加
    @ApiOperation("添加indexProduct的接口(新品,热销)")
    @CacheEvict(value = "indexDetail",key = "'getIndexDetailMap'")
    public ResponseFormat addIndexProduct(@RequestBody @Validated(value = AddGroup.class)
                                                      IndexProduct indexProduct){
        boolean flag = indexProductService.save(indexProduct);
        if(!flag)
            return ResponseFormat.failure("插入失败,数据库错误");
        return ResponseFormat.ok("添加成功",indexProduct);
    }

    //就直接操纵商品上新品或者热销推荐,就两个状态,推荐或者删除
//    @PutMapping("/do-indexProduct")//修改
//    @ApiOperation("修改indexProduct的接口(新品,热销)")
//    public ResponseFormat updateIndexProduct(@RequestBody @Validated(value = UpdateGroup.class)
//                                                         IndexProduct indexProduct){
//        boolean flag = indexProductService.updateById(indexProduct);
//        if(!flag)
//            return ResponseFormat.failure("更新失败,数据库错误");
//        return ResponseFormat.ok("修改成功");
//    }

    @DeleteMapping("/do-indexProduct")//删除
    @ApiOperation("删除indexProduct的接口(新品,热销)")
    @CacheEvict(value = "indexDetail",key = "'getIndexDetailMap'")
    public ResponseFormat deleteIndexProduct(@RequestParam(value = "id")Integer id,
                                             @RequestParam(value = "type")Integer type){
        Map<String,Object> map=new HashMap<>();
        map.put("product_id",id);
        map.put("type",type);
        boolean flag = indexProductService.removeByMap(map);
        if(!flag)
            return ResponseFormat.failure("删除失败,数据库错误");
        return ResponseFormat.ok("删除成功");
    }

    //公告
//    @PutMapping("/do-announcement")
//    @ApiOperation("修改公告的接口")
//    public ResponseFormat announcement(@RequestParam(value = "content")String content){
//        redis.setString(IndexEnum.GONGGAO.getName(),content);
//        return ResponseFormat.ok("公告修改成功");
//    }


    @PostMapping("/news")//一堆新品推荐
    @ApiOperation("批量添加新品推荐")
    @CacheEvict(value = "indexDetail",key = "'getIndexDetailMap'")
    public ResponseFormat addNews(@RequestBody List<Integer> list){
        return indexProductService.addIndexProduct(list,IndexEnum.XINPIN);
    }

    @DeleteMapping("/news")//一堆下架新品推荐
    @ApiOperation("批量取消新品推荐")
    @CacheEvict(value = "indexDetail",key = "'getIndexDetailMap'")
    public ResponseFormat deleteNews(@RequestBody List<Integer> list){

        indexProductService.deleteNewByIds(list,IndexEnum.XINPIN.getCode());

        return ResponseFormat.ok("新品下架成功");
    }

    @PostMapping("/hots")//一堆热销推荐
    @ApiOperation("批量添加热销推荐")
    @CacheEvict(value = "indexDetail",key = "'getIndexDetailMap'")
    public ResponseFormat addHots(@RequestBody List<Integer> list){
        return indexProductService.addIndexProduct(list,IndexEnum.REXIAO);
    }

    @DeleteMapping("/hots")//一堆下架新品推荐
    @ApiOperation("批量取消热销推荐")
    @CacheEvict(value = "indexDetail",key = "'getIndexDetailMap'")
    public ResponseFormat deleteHots(@RequestBody List<Integer> list){

        indexProductService.deleteNewByIds(list,IndexEnum.REXIAO.getCode());

        return ResponseFormat.ok("热销下架成功");
    }

    @PostMapping("/saveSort")
    @ApiOperation("改变list顺序")
    public ResponseFormat sortIndexDetailList(@RequestBody List<Integer> list){
        //传递的是id,所以不用管是什么类型
        if(list==null||list.size()==0){
            return ResponseFormat.ok("ok");
        }
        AtomicInteger i= new AtomicInteger(list.size());
        List<IndexDetail> detailList=new ArrayList<>(list.size());
        list.forEach(l->{
            IndexDetail indexDetail=new IndexDetail();
            indexDetail.setId(l);
            indexDetail.setSort(i.getAndDecrement());
            detailList.add(indexDetail);
        });
        iIndexDetailService.updateBatchById(detailList);
        return ResponseFormat.ok("保存成功");
    }


}
